# -*- coding: utf-8 -*-
"""
字幕生成器
"""

import re
from pathlib import Path
from typing import List, Dict, Any


class SubtitleGenerator:
    """字幕生成器"""

    @staticmethod
    def format_srt_timestamp(t: float) -> str:
        """
        格式化SRT时间戳

        Args:
            t: 时间（秒）

        Returns:
            SRT时间戳字符串
        """
        h = int(t // 3600)
        m = int((t % 3600) // 60)
        s = int(t % 60)
        ms = int((t - int(t)) * 1000)
        return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"

    @staticmethod
    def split_sentences(text: str) -> List[str]:
        """
        分割句子

        Args:
            text: 文本

        Returns:
            句子列表
        """
        parts = re.split(r"(?<=[。！？.!?])\s*", text)
        return [p for p in parts if p.strip()]

    def write_srt_by_proportion(self, text: str, total_duration: float, output_path: Path) -> None:
        """
        按比例生成SRT字幕

        Args:
            text: 文本
            total_duration: 总时长
            output_path: 输出路径
        """
        sentences = self.split_sentences(text)
        if not sentences:
            sentences = [text]

        lengths = [max(1, len(re.sub(r"\s+", "", s))) for s in sentences]
        total_len = sum(lengths)
        cur = 0.0

        output_path.parent.mkdir(parents=True, exist_ok=True)

        with open(output_path, "w", encoding="utf-8") as f:
            for i, (s, l) in enumerate(zip(sentences, lengths), 1):
                dur = total_duration * (l / total_len)
                start = cur
                end = min(total_duration, cur + dur)

                f.write(f"{i}\n")
                f.write(f"{self.format_srt_timestamp(start)} --> {self.format_srt_timestamp(end)}\n")
                f.write(s.strip() + "\n\n")

                cur = end
